<div class="row">
    <div class="col-xs-12">
        <div class="box">
            <div class="box-header">
                <h3 class="box-title">商品管理</h3>

                <div class="box-tools">

                    <div class="input-group input-group-sm" style="width: 505px;">
                        <select id="optionCategoryId" class="btn btn-default btn-option pull-left">
                            <option>所有商品类型</option>
                        </select>
                        <input type="text" name="table_search" id="searchNameId"
                               class="form-control pull-right" placeholder="商品名称" style="width: 250px;">
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-default btn-search">
                                <i class="fa fa-search"></i>
                            </button>
                            <button type="button" class="btn btn-default btn-add">添加</button>
                            <button type="button" class="btn btn-default btn-update">修改</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body table-responsive no-padding">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>选择</th>
                        <th>商品类型</th>
                        <th>商品名称</th>
<!--                        <th>商品图片</th>-->
                        <th>卖点信息</th>
                        <th>促销信息</th>
                        <th>创建时间</th>
                        <th>修改时间</th>
                        <th>销售状态</th>
                        <th>查看配置</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="tbodyId"></tbody>
                </table>
            </div>
            <div id="pageId" class="box-footer clearfix">
            </div>
            <!-- /.box-body -->
        </div>
        <!-- /.box -->
    </div>
</div>
<script type="text/javascript">

    //分页浏览功能
    $(document).ready(function () {
        doLoadCategory();   //商品类型下拉框
        $("#pageId").load("/modules/common/page.html", doGetObjects); //执行方法查询数据加载页面
        $(".input-group-btn")
            .on("click", ".btn-search", doQueryObjects)    //搜索方法
            .on("click", ".btn-add,.btn-update", doLoadEditUI);	//跳转到编辑页面
        $("tbody").on("click", ".btn-type", doTypeById);		//跳转详情页按钮方法
        $("tbody").on("click", ".btn-delete", doDeleteById);		//删除按钮方法
    });

    //商品类型下拉框
    function doLoadCategory() {
        let url = `${baseUrl}/shoppingback/ddCategoryInfo`;
        $.ajax({
            url, crossDomain: true, xhrFields: {withCredentials: true},
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if (result.success) {
                    //1.获取类别要显示的位置对象
                    let div = $("#optionCategoryId");
                    //div.empty();
                    //2.迭代数据，将数据追加到div
                    // <option value="1">选择商品类型</option> <input type='radio' name='roleId' value='[id]'>[name]
                    let option = `<option name='categoryId' value='[id]'>[name]</option>` //载入类型选择
                    result.data.forEach(item => {
                        //记住每次replace时都会产生一个新的字符串对象
                        var newInput =
                            option.replace("[id]", item.id)
                                .replace("[name]", item.categoryName);
                        div.append(newInput)    //插入类型选择
                    });
                } else {
                    alert(result.msg);
                }
            }
        })
    }

    //跳转到商品配置页
    function doTypeById() {
        //基于id进行查询并加载编辑页面
        let typeUrl = "/modules/sys/kind_list.html"
        let id = $(this).parents("tr").data("rowData").id;
        $("#mainContentId").data("pdId", id); //加载数据到页面
        $("#mainContentId").load(typeUrl) //赋予url到修改用户
    }

    //跳转到编辑页面
    function doLoadEditUI() {
        //1.判定点击的对象
        let editUrl = "/modules/sys/item_edit.html"
        if ($(this).hasClass("btn-add")) {
            $("#mainContentId").load(editUrl, () => $(".box-title").html("商品添加"))
        } else if ($(this).hasClass("btn-update")) {
            let id = doGetCheckedId();
            if (!id) {	//如果没选择用户
                alert("请先选择");
                return;
            }
            //基于id进行查询并加载编辑页面
            let findByIdUrl = `${baseUrl}/shoppingback/ddProductInfo/${id}`;
            $.ajax({
                url: findByIdUrl, crossDomain: true, xhrFields: {withCredentials: true},
                headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
                success(result) {//JsonResult
                    if(result.status==401){
                        alert(result.msg);
                        return;
                    }
                    if(result.status==403){
                        alert(result.msg);
                        return;
                    }
                    if (result.success) {
                        $("#mainContentId").data("rowData", result.data); //加载数据到页面
                        $("#mainContentId").load(editUrl, () => $(".box-title").html("商品修改")) //赋予url到修改用户
                    } else {
                        alert(result.msg);
                    }
                }
            });
        }
    }

    //点击id选择用户
    function doGetCheckedId() {
        return $("tbody input[name='radioId']:checked").val();
    }

    //保存页数并显示
    function doLoadPage(title) {

        $("#mainContentId").load(url, function () {
            $(".box-title").html(title);
        })
    }

    //删除按钮
    function doDeleteById() {
        if (!confirm("确定删除该商品及所有配置?")) {
            return;
        }
        let rowData = $(this).parents("tr").data("rowData"); //根据点击对象获取用户的数据
        let id = rowData.id;
        let url = `${baseUrl}/shoppingback/ddProductInfo/${id}`;
        //todo 这里在设置权限管理后再开放
        alert("不允许删除");return;
        $.ajax({
            method: "delete",
            url: url,
            headers: {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            crossDomain: true,
            xhrFields: {withCredentials: true},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if (result.success) {
                    alert(result.msg);
                    doGetObjects();
                } else {
                    alert(result.msg);
                }
            }
        });
    }

    //处理查询按钮事件
    function doQueryObjects() {
        $("#pageId").data("pageNum", 1);
        doGetObjects();
    }

    //页面加载完成异步加载当前页数据
    function doGetObjects() {
        let url = `${baseUrl}/shoppingback/ddProductInfo`;
        let pageNum = $("#pageId").data("pageNum");
        if (!pageNum) pageNum = 1;
        let params = {"pageNum": pageNum}
        params.query = $("#searchNameId").val().trim();
        params.categoryId = ($("#optionCategoryId").val()=="所有商品类型"?null:$("#optionCategoryId").val());
        $.ajax({
            url: url, data: params, crossDomain: true, xhrFields: {withCredentials: true},
            headers: {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if(result.data.rows==null){
                    alert("该商品没有配置明细,请至少添加1条配置才可以售卖")
                }
                if(result.state==403){
                    alert(result.message);
                }
                doHandleQueryResponseResult(result);
            }
        });
    }

    //处理搜索框结果
    function doHandleQueryResponseResult(result) {
        if (result.success) {
            doSetTableBodyRows(result.data.rows);
            doSetPagination(result.data);
        } else {
            alert(result.msg);
        }
    }

    //通过服务端返回的数据初始化页面
    function doSetTableBodyRows(data) {
        //1.获取tbody对象，并清空内容
        let tBody = $("#tbodyId");
        tBody.empty();
        //2.迭代data内容将数据追加到tbody中
        data.forEach(item => {
            let tr = $("<tr></tr>");
            tr.data("rowData", item);
            let tds = doCreateTds(item);
            tr.append(tds);
            tBody.append(tr);
        });
    }

    function doCreateTds(row) {
        return `<td><input type='radio' name='radioId' value='${row.id}' ></td>
         <td>${row.categoryName}</td>
	     <td>${row.pdName}</td>
	     <td>${row.advantage}</td>
	     <td>${row.promotion}</td>
	     <td>${getFormatDate2(row.createTime)}</td>
	     <td>${getFormatDate2(row.updateTime)}</td>
	     <td>${row.saleState==1?"在售":"禁售"}</td>
	     <td><button type='button' class='btn btn-primary btn-type'>详细配置</button></td>
         <td><button type='button' class='btn btn-default btn-delete'>删除</button></td>`;
    }

    function getFormatDate2(time) {
        var nowDate = new Date(time);
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
        var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
        var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
        var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
        var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
        return year + "年" + month + "月" + date + "日" + hour + ":" + minute + ":" + second;
    }
</script>




